package com.gnerv.sylvanas.authentication.security.config.filter;

import com.gnerv.sylvanas.framework.common.model.RestResult;
import com.gnerv.sylvanas.framework.common.model.RestResultCode;
import com.gnerv.sylvanas.framework.core.tools.JsonTools;
import com.gnerv.sylvanas.authentication.security.service.VerificationCodeService;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @Author Gnerv LiGen
 * @create 2023/3/28 15:20
 */
@Slf4j
public class VerificationCodeFilter extends OncePerRequestFilter {

    private final RequestMatcher requestMatcher;

    @Resource
    private VerificationCodeService verificationCodeService;

    public VerificationCodeFilter(String defaultFilterProcessesUrl) {
        this.requestMatcher = new AntPathRequestMatcher(defaultFilterProcessesUrl, "POST");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        boolean matches = requestMatcher.matches(request);
        if (matches) {
            boolean verify = verificationCodeService.verify(request, response);
            if (!verify) {
                // 验证码对比不通过
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                response.setCharacterEncoding(StandardCharsets.UTF_8.name());
                PrintWriter writer = response.getWriter();
                writer.println(JsonTools.toJsonString(RestResult.error(RestResultCode.CODE_408, "Verification Code Error !")));
                writer.close();
            } else {
                filterChain.doFilter(request, response);
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }
}
